<template>
  <div class="app-container">
     <!-- 按钮 开始-->
    <el-card class="box-card">
      <div style="text-align:right;">
        <el-button type="primary" icon="el-icon-plus" :disabled="isSubmit" size="small" @click="handleAddMedicines">添加药品</el-button>
        <el-button type="success" icon="el-icon-s-operation" :disabled="isSubmit" size="small" @click="handleBatchSet">批量设置</el-button>
        <el-button type="warning" icon="el-icon-check" :disabled="isSubmit" size="small" @click="handleSubmit">暂存</el-button>
        <el-button type="danger" icon="el-icon-finished" :disabled="isSubmit" size="small" @click="handleSubmitAndAudit">提交审核</el-button>
      </div>
    </el-card>
      <!-- 按钮 结束-->
       <!-- 主单据信息显示开始-->
    <el-card class="box-card">
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="68px">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item label="单据号" prop="purchaseId">
              <el-input
                v-model="form.purchaseId"
                placeholder="请输入单据号"
                :disabled="true"
                size="small"
                style="width:220px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="供应商" prop="providerId">
              <el-select
                v-model="form.providerId"
                placeholder="请选择供应商"
                size="small"
                style="width:220px"
                clearable
              >
                <el-option
                  v-for="d in providerOptions"
                  :key="d.providerId"
                  :label="d.providerName"
                  :value="d.providerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="总批发额" prop="purchaseTradeTotalAmount">
              <el-input
                v-model="form.purchaseTradeTotalAmount"
                placeholder="请输入总批发额"
                :disabled="true"
                size="small"
                style="width:220px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="制单人" prop="purchaseTradeTotalAmount">
              <el-input
                v-model="form.createBy"
                placeholder="请输入制单人"
                :disabled="true"
                size="small"
                style="width:220px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="制单时间" prop="purchaseTradeTotalAmount">
              <el-input
                v-model="form.createTime"
                placeholder="请输入制单时间"
                :disabled="true"
                size="small"
                style="width:220px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </el-card>
    <!-- 主单据信息显示结束-->
    <!--详情信息显示开始-->
    <el-card class="box-card">
      <el-table
    :data="PurchaseItemTableList"
    stripe
    style="width: 100%">
    <el-table-column prop="medicinesId" label="药品ID" align="center"  />
    <el-table-column prop="medicinesName" label="药品名称" align="center"  />
    <el-table-column prop="" label="规格" align="center"  >
      <template slot-scope="scope">
        <span>{{scope.row.conversion}}{{scope.row.unit}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="producterId" label="生产厂家" align="center" :formatter="producterFormatter"  />
    <el-table-column prop="purchaseNumber" label="数量"  align="center" >
       <template slot-scope="scope">
       <el-input-number
              v-model="scope.row.purchaseNumber"
              :step="1"
              :min="10"
              size="small"
            />
        </template>
    </el-table-column>
    
    <el-table-column prop="unit" label="单位"   align="center" />
    <el-table-column prop="tradePrice" label="批发价"  align="center" >
      <template slot-scope="scope">
      <el-input-number
              v-model="scope.row.tradePrice"
              :min="0"
              :step="0.1"
              :precision="2"
              size="small"
            />
      </template>
    </el-table-column>
    <el-table-column prop="tradeTotalAmount" label="批发额"  align="center"  >
      <template slot-scope="scope">
        <span>{{scope.row.tradeTotalAmount | routing }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="batchNumber" label="批次号"  align="center"  >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.batchNumber"
              size="small"
            />
          </template>
    </el-table-column>
    <el-table-column prop="remark" label="备注"  align="center"  >
       <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              size="small"
            />
          </template>
    </el-table-column>
    <el-table-column  label="操作"  align="center"  >
      <template slot-scope="scope">
         <el-button type="danger" round :disabled="isSubmit"  @click="handleDelete(scope.$index,scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    </el-card>
<!--详情信息显示结束-->
  <!-- 药品列表的弹出层开始 -->
    <el-dialog
      :title="title"
      :visible.sync="medicinesOpen"
      width="1100px"
      center
      append-to-body
    >
      <!-- 查询条件开始 -->
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="120px">

        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入关键字"
            clearable
            size="small"
            style="width:180px"
          />
        </el-form-item>
        <el-form-item label="药品类型" prop="medicinesType">
          <el-select
            v-model="queryParams.medicinesType"
            placeholder="药品类型"
            clearable
            size="small"
            style="width:180px"
          >
            <el-option
              v-for="dict in medicinesTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="处方类型" prop="prescriptionType">
          <el-select
            v-model="queryParams.prescriptionType"
            placeholder="处方类型"
            clearable
            size="small"
            style="width:180px"
          >
            <el-option
              v-for="dict in prescriptionTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 查询条件结束 -->

      <!-- 药品的数据表格开始 -->
      <el-table ref="medicinesTableList" v-loading="loading" border :data="medicinesTableList" @selection-change="handleSelectionChnage">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="药品ID" align="center" prop="medicinesId" />
        <el-table-column label="药品名称" align="center" prop="medicinesName" />
        <el-table-column label="药品编号" align="center" prop="medicinesNumber" />
        <el-table-column label="生产厂家" width="280px" align="center" prop="producterId" :formatter="producterFormatter" />
        <el-table-column label="药品类型" align="center" prop="medicinesType" :formatter="medicinesTypeFormatter" />
        <el-table-column label="处方类型" align="center" prop="prescriptionType" :formatter="prescriptionTypeFormatter" />
        <el-table-column label="关键字" align="center" prop="keywords" />
      </el-table>
      <!-- 药品的数据表格结束 -->
      <!-- 分页控件开始 -->
      <el-pagination
        v-show="total>0"
        :current-page="queryParams.pageNum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    <!-- 分页控件结束 -->
    </el-dialog>
    <!-- 药品列表的弹出层结束 -->
  <!--添加药品弹出层开始-->
  <!--批量设置弹出层开始-->
 <el-dialog
      :title="title"
      :visible.sync="batchSetOpen"
      width="500px"
      center
      append-to-body
    >
      <el-form ref="batchSetForm" :model="batchSetForm" label-width="100px">
        <el-form-item label="数量" prop="purchaseNumber">
          <el-input-number v-model="batchSetForm.purchaseNumber" placeholder="请输入数量" size="small" />
        </el-form-item>
        <el-form-item label="批发价格" prop="tradePrice">
          <el-input-number v-model="batchSetForm.tradePrice" :precision="2" placeholder="请输入数量" size="small" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="batchSetForm.batchNumber" placeholder="请输入批次号" size="small" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="batchSetForm.remark" placeholder="请输入备注" size="small" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchSetSubmit">确定</el-button>
        <el-button @click="cancelBatchSet">取消</el-button>
      </span>
    </el-dialog>

   <!--批量设置弹出层结束-->
  </div>
</template>
<script>
import {generatePurchaseId,addPurchase,addPurchaseToAudit,queryPurchaseAndItemByPurchaseId} from '@/api/erp/purchase'
import {selectAllProvider} from '@/api/erp/provider'
import {listMedicinesForPage} from '@/api/erp/medicines'
import {selectAllProducter} from '@/api/erp/producter'
export default {

  filters:{
      routing(val){
          return val.toFixed(2)
      }
  },

  data(){
    return {
      loading:false,
      //主单据form
      form:{},
      //供应商数据
      providerOptions:[],
      //数据校验
      rules:{
        providerId:[
            { required: true, message: '供应商名称不能为空', trigger: 'blur' }
        ]
      },
     

      //提交之后是否显示按钮
      isSubmit:true,
      //弹出层标题
      title:'',
      //药品列表:弹出层是否显示
      medicinesOpen:false,
      //批量设置弹出层
      batchSetOpen:false,
      queryParams:{
        keywords:undefined,
        medicinesType:undefined,
        prescriptionType:undefined,
        pageNum : 1,
        pageSize : 10
      },
      medicinesTableList:[],
      total:0,
      //药品类型数据字典
      medicinesTypeOptions:[],
      //处方类型数据字典
      prescriptionTypeOptions:[],
      //生产厂家数据
      producterOptions:[],
      //单据详情
      PurchaseItemTableList:[],
      //选中药品数据集合
      selectMedicinesList:[],
      batchSetForm:{}

      
    } 
  },
  created(){
    //自动生成单号
    generatePurchaseId().then(res =>{
      this.form = res.data
    })
    //初始化供应商数据
    selectAllProvider().then(res =>{
      this.providerOptions = res.data
    })
    //初始化药品类型字典数据
    this.getDataByType('his_medicines_type').then(res =>{
      this.medicinesTypeOptions = res.data
    })
     //初始化处方类型字典数据
    this.getDataByType('his_prescription_type').then(res =>{
      this.prescriptionTypeOptions = res.data
    })
    //初始化厂家字典数据
    selectAllProducter().then(res =>{
      this.producterOptions = res.data
    })
    //初始化药品数据
    this.getlistMedicinesForPage()

    //初始化单据和详情
    this.initEdit()
    
  },
  methods:{

    initEdit(){
      const purchaseId  = this.$route.params.purchaseId
      queryPurchaseAndItemByPurchaseId(purchaseId).then(res =>{
        this.PurchaseItemTableList = res.data.items 
        this.form = res.data.purchase
        this.form.providerId = parseInt(res.data.purchase.providerId)
        if (res.data.purchase.status === '1' || res.data.purchase.status === '4') {
        this.isSubmit = false
      }

      })
    },
    //查询药品数据
    getlistMedicinesForPage(){
      return new Promise(resolve =>{
      this.loading = true
      listMedicinesForPage(this.queryParams).then(res =>{
        this.medicinesTableList = res.data
        this.total = res.total
        this.loading = false
        resolve()
         })
      })
      
    },
    //添加药品
    handleAddMedicines(){
        this.medicinesOpen = true
        this.Fcheck()
       
    },
    //反选
    Fcheck(){
     
      if(this.$refs.medicinesTableList!==undefined){
        this.$refs.medicinesTableList.clearSelection();
        }
         //反选之前有的
        this.PurchaseItemTableList.map(item =>{
          this.medicinesTableList.map(item1 =>{
            if(parseInt(item1.medicinesId) === parseInt(item.medicinesId)){
                this.$refs.medicinesTableList.toggleRowSelection(item1,true);
            }
          })
        })
    },
    //批量设置
    handleBatchSet(){
      this.resetForm('batchSetForm')
      this.batchSetOpen= true

    },
    //暂存
    handleSubmit(){
      
       this.$refs['form'].validate((valid) => {
        if (valid) {
          // 做添加
          const purchaseForm = {"purchaseDto":this.form,'purchaseItemDto': this.PurchaseItemTableList}
          addPurchase(purchaseForm).then(res =>{
              this.msgSuccess("暂存成功")
          })
          
          } 
        })
    },
    //提交审核
    handleSubmitAndAudit(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 做添加
          const purchaseForm = {"purchaseDto":this.form,'purchaseItemDto': this.PurchaseItemTableList}
          addPurchaseToAudit(purchaseForm).then(res =>{
              this.msgSuccess("提交成功")
              this.isSubmit=true
          })
          } 
        })

    },
    //删除一条详情
    handleDelete(index,row){
      this.PurchaseItemTableList.splice(index,1)
    },
    //新增药品选中触发事件
    handleSelectionChnage(selection){
      // console.log(selection)
      this.selectMedicinesList = selection
      this.selectMedicinesList.filter(m1 => {
        let flag = false
        // 判断purchaseItemList里面有没有已选择的ID
        this.PurchaseItemTableList.filter(purch => {
          if (m1.medicinesId === purch.medicinesId) {
            flag = true
          }
        })
        // 如果没有，就加入purchaseItemList
        if (!flag) {
          // 放到purchaseItemList对象是selection深度clone
          this.PurchaseItemTableList.push(JSON.parse(JSON.stringify(m1)))
        }
      })
     // 剔除里面不用的属性，添加需要的属性
      this.PurchaseItemTableList.filter(m => {
        this.$delete(m, 'status')
        this.$delete(m, 'medicinesStockNum')
        this.$delete(m, 'medicinesStockDangerNum')
        this.$delete(m, 'createTime')
        this.$delete(m, 'updateTime')
        this.$delete(m, 'createBy')
        this.$delete(m, 'updateBy')

        this.$set(m, 'purchaseNumber', m.purchaseNumber ? m.purchaseNumber : 10)
        this.$set(m, 'tradePrice', m.tradePrice ? m.tradePrice : 0.00)
        this.$set(m, 'tradeTotalAmount', m.tradeTotalAmount ? m.tradeTotalAmount : 0.00)
        this.$set(m, 'batchNumber', m.batchNumber ? m.batchNumber : '')
        this.$set(m, 'remark', m.remark ? m.remark : '')
      })


    },
    //药品分页
    handleSizeChange(val){
        this.queryParams.pageSize = val
        this.getlistMedicinesForPage().then(res =>{
          this.Fcheck()
        })
        
        
    },
    handleCurrentChange(val){
        this.queryParams.pageNum = val
        this.getlistMedicinesForPage().then(res =>{
          this.Fcheck()
        })
        
    },
    //翻译生产厂家
    producterFormatter(row){
        let name = ''
        this.producterOptions.map(item =>{
          if(parseInt(item.producterId) === parseInt(row.producterId)){
            name = item.producterName
          }
        })
        return name
    },
    //翻译药品类型
    medicinesTypeFormatter(row){
    return this.selectDictLabel(this.medicinesTypeOptions,row.medicinesType)
    },
    //翻译处方类型
    prescriptionTypeFormatter(row){
     return this.selectDictLabel(this.prescriptionTypeOptions,row.prescriptionType)
    },
    handleBatchSetSubmit(){
      if(this.PurchaseItemTableList.length>0){
      this.PurchaseItemTableList.map(item =>{
          item.purchaseNumber = this.batchSetForm.purchaseNumber
          item.tradePrice = this.batchSetForm.tradePrice
          item.batchNumber = this.batchSetForm.batchNumber
          item.remark = this.batchSetForm.remark
          this.msgSuccess("设置成功")
          this.batchSetOpen = false
      })
      }else{
        this.msgError("找不到对应的项")
      }

    },
    cancelBatchSet(){
      this.batchSetOpen = false
    }
  },
  watch:{
    
   'queryParams.keywords':{
      handler(newVal,oldVal){
        this.queryParams.pageNum = 1
        this.getlistMedicinesForPage().then(res =>{
          this.Fcheck()
        })
      },
       deep:true
    },
    'queryParams.medicinesType':{
      handler(newVal,oldVal){
        this.queryParams.pageNum = 1
        this.getlistMedicinesForPage().then(res =>{
          this.Fcheck()
        })
      },
       deep:true
    },
    'queryParams.prescriptionType':{
      handler(newVal,oldVal){
        this.queryParams.pageNum = 1
        this.getlistMedicinesForPage().then(res =>{
          this.Fcheck()
        })
      },
       deep:true
    },
    PurchaseItemTableList:{
      handler(newVal,oldVal){
        this.form.purchaseTradeTotalAmount = 0.00
         this.PurchaseItemTableList.map(item =>{
           item.tradeTotalAmount = item.tradePrice*item.purchaseNumber
           console.log(this.form.purchaseTradeTotalAmount)
           this.form.purchaseTradeTotalAmount += item.tradeTotalAmount
         })
      },
      deep:true
    }
    
  }
}

</script>
<style scoped>
  .box-card{
    padding: 0px;
    margin: 0px;
    margin-bottom: 8px;
  }
</style>
